//
//  WPAddPEFVC.m
//  wobingwoyi
//
//  Created by WGP on 2017/3/1.
//  Copyright © 2017年 WGP. All rights reserved.
//

#import "WPAddPEFVC.h"
#import "WPPEFFirstTableViewCell.h"
#import "WPPEFSecondTableViewCell.h"
#import "WPPEFThirdTableViewCell.h"
#import "TZImagePickerController.h"
#import "TZTestCell.h"
#import "WPHomeEditeImageVC.h"
#import "WPPhotoPreviewController.h"
#import "HMDatePicker.h"
#import "LxGridViewFlowLayout.h"

@interface WPAddPEFVC ()<UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource,TZImagePickerControllerDelegate,HMDatePickerDelegate>

@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)UIButton *uploadBtn;
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)LxGridViewFlowLayout *layout;
@property(nonatomic,assign)CGFloat secondCellHeight;
@property(nonatomic,strong)UILabel *timeLabel;
@property(nonatomic,strong)NSMutableArray *selectedPhotos;
@property(nonatomic,strong)NSMutableArray *selectedAssets;
@property(nonatomic,strong)NSMutableArray *snapImagesArr;
@property(nonatomic,assign)BOOL isSelectOriginalPhoto;

@end

@implementation WPAddPEFVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.titleLabel.text = @"体检档案";
    self.view.backgroundColor = GlobalBgColor;
    
    [self setupUI];
}


-(void)setupUI
{
    self.selectedAssets = [NSMutableArray array];
    self.selectedPhotos = [NSMutableArray array];
    [self tableView];
    [self uploadBtn];
}

-(UITableView *)tableView
{
    if (_tableView == nil)
    {
        _tableView  = [[UITableView alloc] init];
        [self.view addSubview:_tableView];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.bounces = NO;
        _tableView.backgroundColor =GlobalBgColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[WPPEFFirstTableViewCell class] forCellReuseIdentifier:@"WPPEFFirstTableViewCell"];
        [_tableView registerClass:[WPPEFSecondTableViewCell class] forCellReuseIdentifier:@"WPPEFSecondTableViewCell"];
         [_tableView registerClass:[WPPEFThirdTableViewCell class] forCellReuseIdentifier:@"WPPEFThirdTableViewCell"];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.view);
            make.top.equalTo(self.navBarView.mas_bottom);
            make.bottom.equalTo(self.view).offset(-45);
        }];
    }
    return _tableView;
}

-(UIButton *)uploadBtn
{
    if (_uploadBtn == nil)
    {
        _uploadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_uploadBtn setBackgroundColor:[UIColor whiteColor]];
        [_uploadBtn setTitle:@"上传" forState:UIControlStateNormal];
        _uploadBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_uploadBtn setTitleColor:GLobalFontColor forState:UIControlStateNormal];
        [_uploadBtn addTarget:self action:@selector(uploadBtnDidClick) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_uploadBtn];
        [_uploadBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
            make.height.mas_equalTo(45);
        }];
    }
    return _uploadBtn;
}

-(void)uploadBtnDidClick
{
    
}

-(CGFloat)secondCellHeight
{
    CGFloat width = (SCREEN_WIDTH - 5*10)/4.0;
    NSInteger count = self.selectedPhotos.count;
    _secondCellHeight = (count / 4 + 1)*width + count / 4 * 10;
    return _secondCellHeight;
}

#pragma mark - UITableView的代理方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.item == 0)
    {
        return [tableView dequeueReusableCellWithIdentifier:@"WPPEFFirstTableViewCell" forIndexPath:indexPath];
    }
    else if(indexPath.item == 1)
    {
       WPPEFThirdTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WPPEFThirdTableViewCell" forIndexPath:indexPath];
        self.collectionView = cell.collectionView;
        self.layout = cell.layout;
        cell.collectionView.delegate = self;
        cell.collectionView.dataSource = self;
        cell.collectionView.backgroundColor = [UIColor whiteColor];
        [cell.collectionView registerClass:[TZTestCell class] forCellWithReuseIdentifier:@"TZTestCell"];
        return cell;
    }
    else
    {
        
        WPPEFSecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WPPEFSecondTableViewCell" forIndexPath:indexPath];
        self.timeLabel = cell.timeLabel;
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.item == 0)
    {
        return 160;
    }
    else if (indexPath.item == 1)
    {
        return self.secondCellHeight + 30;
    }
    else
    {
        return 54;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.item == 2)
    {
        // 创建日期选择器
        HMDatePicker *pickerView = [HMDatePicker datePicker];
        // 设置代理
        pickerView.delegate = self;
        // 设置datePicker当前显示的时间
        if (![self.timeLabel.text isEqualToString:@"请选择时间"])
        {
            pickerView.currentDate =  [[WPDateFormatterManager sharedManager] dateFromString:self.timeLabel.text format:@"yyyy-MM-dd"];
        }
        // 显示
        [pickerView show];
    }
}

#pragma mark - 时间选择器的代理方法
- (void)datePickerDidValueChanged:(HMDatePicker *)datePicker
{
     self.timeLabel.text = [[WPDateFormatterManager sharedManager] stringFromDateWithDate:datePicker.datePicker.date format:@"yyyy-MM-dd"];
    self.timeLabel.textColor = GLobalFontColor;
}


#pragma mark - UICollectionView的数据源方法
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.selectedPhotos.count+1;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TZTestCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TZTestCell" forIndexPath:indexPath];
    cell.videoImageView.hidden = YES;
    if (indexPath.row == self.selectedPhotos.count) {
        cell.imageView.image = [UIImage imageNamed:@"AlbumAddBtn.png"];
        cell.deleteBtn.hidden = YES;
    } else {
        cell.imageView.image = self.snapImagesArr[indexPath.row];
        cell.asset = self.selectedAssets[indexPath.row];
        cell.deleteBtn.hidden = NO;
    }
    cell.deleteBtn.tag = indexPath.row;
    [cell.deleteBtn addTarget:self action:@selector(deleteBtnClik:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == _selectedPhotos.count) {
        
        [self pushImagePickerController];
        
    } else { // preview photos or video / 预览照片或者视频
        
        // preview photos / 预览照片
        WPPhotoPreviewController *ppc = [WPPhotoPreviewController new];
        ppc.photos = _selectedPhotos;
        ppc.currentIndex = indexPath.item;
        [self presentViewController:ppc animated:YES completion:nil];
    }
}

#pragma mark - TZImagePickerController

- (void)pushImagePickerController {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:12 delegate:self];
    
#pragma mark - 四类个性化设置，这些参数都可以不传，此时会走默认设置
    imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
    
    // 1.如果你需要将拍照按钮放在外面，不要传这个参数
    imagePickerVc.selectedAssets = self.selectedAssets; // optional, 可选的
    imagePickerVc.allowTakePicture = YES; // 在内部显示拍照按钮
    
    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = YES;
    
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = NO;
    
#pragma mark - 到这里为止
    
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
        
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

#pragma mark Click Event

- (void)deleteBtnClik:(UIButton *)sender {
    [self.selectedPhotos removeObjectAtIndex:sender.tag];
    [self.selectedAssets removeObjectAtIndex:sender.tag];
    self.layout.itemCount = _selectedPhotos.count;
    
    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
    [self.collectionView performBatchUpdates:^{
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:sender.tag inSection:0];
        [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
    } completion:^(BOOL finished) {
        [self.collectionView reloadData];
    }];
}

- (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)sourceIndexPath didMoveToIndexPath:(NSIndexPath *)destinationIndexPath {
    if (sourceIndexPath.item >= _selectedPhotos.count || destinationIndexPath.item >= _selectedPhotos.count) return;
    UIImage *image = _selectedPhotos[sourceIndexPath.item];
    if (image) {
        [_selectedPhotos exchangeObjectAtIndex:sourceIndexPath.item withObjectAtIndex:destinationIndexPath.item];
        [_selectedAssets exchangeObjectAtIndex:sourceIndexPath.item withObjectAtIndex:destinationIndexPath.item];
        [_collectionView reloadData];
    }
}

#pragma mark - TZImagePickerControllerDelegate

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    self.selectedPhotos = [NSMutableArray arrayWithArray:photos];
    self.selectedAssets = [NSMutableArray arrayWithArray:assets];
    self.isSelectOriginalPhoto = isSelectOriginalPhoto;
    self.layout.itemCount = self.selectedPhotos.count;
    
    [self.snapImagesArr removeAllObjects];
    for (UIImage *image in photos)
    {
        NSData *data = UIImageJPEGRepresentation(image, 0.3);
        UIImage *snapImage = [UIImage imageWithData:data];
        [self.snapImagesArr addObject:snapImage];
    }
    
    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
    [self.collectionView reloadData];
}

-(NSMutableArray *)snapImagesArr
{
    if (_snapImagesArr == nil)
    {
        _snapImagesArr = [NSMutableArray array];
    }
    return _snapImagesArr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
